import 'dart:async';
import 'dart:io';

import 'package:get/get.dart';
import 'package:shimo_app/bus/bus.dart';
import 'package:shimo_app/bus/struct/log.dart';
import 'package:shimo_app/pages/components/hint.dart';
import 'package:shimo_app/services/db_service.dart';
import 'package:shimo_app/bus/struct/task_progress.dart';

import '../../bus/struct/task_progress.dart';
import '../../services/device_service.dart';
import 'function/function_controller.dart';
import 'sample_state.dart';
import '../components/durationDialog.dart';

import '../../vision/tube_detector.dart';

/// 样品控制控制器
/// 负责管理样品处理任务的生命周期、状态监控和用户交互
class SampleController extends GetxController {
  final SampleState state = SampleState();
  final DeviceService deviceService = Get.find<DeviceService>();

  // 数据库服务（当前注释未使用）
  // final DbService dbService=Get.find<DbService>();

  // 任务运行状态：[模块1运行中, 模块2运行中]
  List<bool> working = [false, false];
  // 任务暂停状态：[模块1暂停, 模块2暂停]
  List<bool> pause = [false, false];
  // 当前任务进度信息（双模块）
  List<TaskProgress> currentTaskProgress = [
    TaskProgress(-1, -1, -1, TaskState.EMPTY),
    TaskProgress(-1, -1, -1, TaskState.EMPTY)
  ];

  // 事件监听器订阅列表，用于资源清理
  List<StreamSubscription> _events = [];

  // 实时传感器数据（双模块）
  List<double> currentTemperatureValue = [0, 0]; // 当前温度值
  List<double> currentHeatPower = [0, 0]; // 当前加热功率
  List<double> targetTemperatureValue = [0, 0]; // 设定温度值
  List<double> currentUltrasonic1 = [0, 0]; // 超声波传感器值
  List<double> remainingtime = [0, 0]; // 剩余时间
  List<double> allTime = [0, 0]; //总时间
  // 实时机械臂位置数据
  List<double> currentArmXPosition = [0, 0]; // X轴位置 [容器0, 容器1]
  List<double> currentArmYPosition = [0, 0]; // Y轴位置 [容器0, 容器1]

  // 新进度事件到达标志（避免重复处理）
  List<bool> _newProgressEventIn = [false, false];

  // 样品位状态数据（三维数组：[模块][行][列]）
  final List<List<List<SampleItem>>> sampleItems = [[], []];

  // 日志记录（双模块）
  List<List<LocalLog>> logList = [[], []];

  // 日志文件句柄
  List<File> logFiles = [];

  // 总线连接状态
  bool busConnected = false;
  int busState = -1;

  @override
  void onInit() async {
    // 初始化样品位网格数据结构
    for (var i = 0; i < deviceService.sampleSize[1]; i++) {
      sampleItems[0].add(List.generate(
          deviceService.sampleSize[0],
          (index) =>
              SampleItem(false, (index + 1).toString(), TaskState.EMPTY)));
      sampleItems[1].add(List.generate(
          deviceService.sampleSize[0],
          (index) =>
              SampleItem(false, (index + 1).toString(), TaskState.EMPTY)));
    }

    // 监听任务事件总线
    _events.add(deviceService.eventBus.on<TaskEvent>().listen((event) {
      // 更新当前任务进度
      currentTaskProgress[event.event.containerId] = event.event;
      _newProgressEventIn[event.event.containerId] = true;

      // 处理有效任务（非255标识符）
      if (currentTaskProgress[event.event.containerId].taskId != 255) {
        final labels = Get.find<FunctionController>()
            .useFunctionLabelList[event.event.containerId];

        print("event.event.containerId:${event.event.containerId}");
        print(
            "currentTaskProgress[event.event.containerId].taskId:${currentTaskProgress[event.event.containerId].taskId}");
        print(
            "labels[currentTaskProgress[event.event.containerId].taskId]:${labels[currentTaskProgress[event.event.containerId].taskId]}");

        final task =
            labels[currentTaskProgress[event.event.containerId].taskId];

        // 如果是加热任务，提取目标温度参数
        if (task.isNotEmpty && task.first == "加热") {
          for (var j = 1; j < task.length; j++) {
            if (task[j] == "目标温度") {
              targetTemperatureValue[event.event.containerId] =
                  double.parse(task[j + 1]);
              print("----刷新目标温度${targetTemperatureValue}");
              break;
            }
          }
        }

        // 记录任务状态变更日志
        if (currentTaskProgress[event.event.containerId].taskId != 255 &&
            task.isNotEmpty) {
          // deviceService.addSystemLog(event.event.containerId,
          // "任务：${task.first};状态:${currentTaskProgress[event.event.containerId].state.name};\n位置:${currentTaskProgress[event.event.containerId].pos + 1};超声波值：${currentUltrasonic1[event.event.containerId]};\nX轴:${currentArmXPosition[event.event.containerId]};Y轴:${currentArmYPosition[event.event.containerId]}");
          deviceService.addSystemLog(event.event.containerId,
              "任务：${task.first};状态:${currentTaskProgress[event.event.containerId].state.name};\n位置:${currentTaskProgress[event.event.containerId].pos + 1};");
          // 延迟处理特定任务类型的附加日志
          300.milliseconds.delay();
          if (task.first == "定容") {
            deviceService.addSystemLog(event.event.containerId,
                "超声波值:${currentUltrasonic1[event.event.containerId]}mV");
          }

          // 更新对应样品位的状态
          final pos = currentTaskProgress[event.event.containerId].pos + 1;
          final i = sampleItems[event.event.containerId]
                  [(pos / deviceService.sampleSize[0]).ceil() - 1]
              [(pos - 1) % deviceService.sampleSize[0]];
          i.state = currentTaskProgress[event.event.containerId].state;
        }
      }

      print(
          ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>${currentTaskProgress[event.event.containerId].taskId}-${currentTaskProgress[event.event.containerId].pos}-${currentTaskProgress[event.event.containerId].state}");
      update();
    }));

    // 监听本地日志事件
    _events.add(deviceService.eventBus.on<LocalLog>().listen((event) {
      logList[event.index].add(event);
      update();

      // 将日志写入文件
      if (logFiles.length >= event.index + 1) {
        logFiles[event.index].writeAsString(
            "${DateTime.fromMillisecondsSinceEpoch(event.time * 1000).toString().substring(0, 19)}-${event.type.name}-${event.content}\n",
            mode: FileMode.append);
      }
    }));

    // 监听调试日志事件
    _events.add(deviceService.eventBus.on<DebugLog>().listen((event) {
      final now = (DateTime.now().second / 1000) as int;

      // 广播日志（containerId = -1）
      if (event.containerId == -1) {
        int id = 0;
        for (var i in logList) {
          if (logFiles.length >= logList.length) {
            logFiles[id].writeAsString(
                "${DateTime.fromMillisecondsSinceEpoch(now * 1000).toString().substring(0, 19)}-${LogType.debugLog}-${event.content}\n",
                mode: FileMode.append);
          }
          i.add(LocalLog(id++, now, LogType.debugLog, event.content));
        }
        return;
      }

      // 指定模块的调试日志
      if (event.containerId > 1) {
        logList[event.containerId].add(
            LocalLog(event.containerId, now, LogType.debugLog, event.content));
        if (logFiles.length >= event.containerId + 1) {
          logFiles[event.containerId].writeAsString(
              "${DateTime.fromMillisecondsSinceEpoch(now * 1000).toString().substring(0, 19)}-${LogType.debugLog}-${event.content}\n",
              mode: FileMode.append);
        }
      }
    }));

    // 延迟初始化日志系统
    Future.microtask(() async {
      await 1000.milliseconds.delay();

      // 初始化日志路径和文件
      final logPath = deviceService.logPath;
      if (logPath != null) {
        final logDir = Directory(logPath);
        if (logDir.existsSync()) {
          // 创建模块日志目录
          final module1Dir = Directory(logPath + "/m1");
          final module2Dir = Directory(logPath + "/m2");
          if (!module1Dir.existsSync()) {
            await module1Dir.create();
          }
          if (!module2Dir.existsSync()) {
            await module2Dir.create();
          }

          // 创建今日日志文件
          final today = DateTime.now().toString().substring(0, 10);
          final logFile1 = File(logPath + "/m1/$today.log");
          if (!logFile1.existsSync()) {
            await logFile1.create();
          }
          final logFile2 = File(logPath + "/m2/$today.log");
          if (!logFile2.existsSync()) {
            await logFile2.create();
          }

          logFiles.add(logFile1);
          logFiles.add(logFile2);
        }
      }
    });

    // 设置总线连接状态监听器
    deviceService.setBusConnectedListener((p0, p1) {
      busConnected = p0;
      busState = p1;
      update();
    });
    super.onInit();
    startArmPositionMonitoring();
  }

  @override
  void dispose() {
    // 清理所有事件监听器
    for (var i in _events) {
      i.cancel();
    }
    super.dispose();
  }

  @override
  void close() {
    super.onClose();
  }

  //持续获取机械臂位置和超声波值
  void startArmPositionMonitoring() {
    Timer.periodic(const Duration(milliseconds: 1500), (timer) async {
      for (int i = 0; i < currentArmXPosition.length; ++i) {
        currentArmXPosition[i] = await getArmPositionXValue();
        currentArmYPosition[i] = await getArmPositionYValue();
        currentUltrasonic1[0] = await getUltrasonic1();
        currentUltrasonic1[1] = await getUltrasonic1();
      }
    });
  }

  /// 运行任务
  /// [containerId] 模块ID（0或1）
  /// 返回任务执行结果
  Future<bool> runTask(int containerId) async {
    _newProgressEventIn[containerId] = false;

    // 非暂停模式下的任务启动验证
    if (!pause[containerId]) {
      final usedFunctionList =
          Get.find<FunctionController>().useFunctionList[containerId];

      // 验证任务列表是否为空
      if (usedFunctionList.isEmpty) {
        showHint("未选择任务", HintType.DANGER);
        return false;
      }

      // 检查选中的样品位
      bool existedSample = false;
      List<bool> selectedSample = [];
      for (var i in sampleItems[containerId]) {
        for (var item in i) {
          // 重置故障状态为完成状态
          if (item.state == TaskState.FAULT) {
            item.state = TaskState.DONE;
          }
        }
        selectedSample.addAll(List.generate(i.length, (index) {
          if (i[index].selected) {
            existedSample = true;
          }
          return i[index].selected;
        }));
      }

      // 验证是否有选中的样品
      if (!existedSample) {
        showHint("未选择样品", HintType.DANGER);
        return false;
      }

      // 构建任务部署数据
      List<TaskDeployData> tasks = [];
      for (var i in usedFunctionList) {
        final funcIndex = i.keys.first; //对应任务索引
        int funcId = funcIndex + 1;
        final params = i.values.first; //任务内容参数 可能有1 ~ 3个

        // 参数数量验证
        if (params.length > 3) {
          showHint("参数数目超过3个", HintType.DANGER);
          return false;
        }

        tasks.add(TaskDeployData(
            funcId,
            params.isEmpty ? 0 : params[0],
            params.length < 2 ? 0 : params[1],
            params.length < 3 ? 0 : params[2]));
      }

      // 更新任务状态
      working[containerId] = true;
      pause[containerId] = false;
      update();

      showHint("开始下发任务", HintType.SUCCESS);
      deviceService.addOperationLog(containerId, "执行任务");

      // 部署样品和任务
      bool r = await deviceService.deploySamplesAndTasks(
        containerId,
        selectedSample,
        tasks,
      );

      if (!r) {
        showHint("开始下发失败", HintType.DANGER);
        return false;
      }
    } else {
      // 暂停后恢复任务
      await deviceService.resume();
    }

    // 任务执行监控循环
    await 200.milliseconds.delay();
    bool done = false;
    int timeoutCount = 0;
    bool result = false;
    int delayDuration = 10;
    int lastTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    int refreshTemplateTime = lastTime;
    int c = lastTime;

    // 初始化传感器数据
    currentTemperatureValue[0] = await getTemperatureValue();
    currentTemperatureValue[1] = await getTemperatureValue1();
    currentHeatPower[0] = await getHeatPower();
    currentHeatPower[1] = await getHeatPower1();
    // currentUltrasonic1[0] = await getUltrasonic1();
    // currentUltrasonic1[1] = await getUltrasonic1();
    //时间检测初始化
    remainingtime[0] = await getremainingtime();
    remainingtime[1] = await getremainingtime1();
    allTime[0] = remainingtime[0];
    allTime[1] = remainingtime[1];
    update();

    print("<<<<<<<<<<<<<<<<<<<<<<<<$_newProgressEventIn");
    deviceService.eventBus.fire(DeviceWorkEvent(true));

    // 双模块启动间隔提示
    if (!working[0] || !working[1]) {
      showDurationDialog30s("开始另一模组请等待...");
    }

    // 任务执行监控循环
    while (working[containerId]) {
      // 定期刷新温度数据（每2秒）
      if (c - refreshTemplateTime > 2) {
        refreshTemplateTime = c;
        currentTemperatureValue[0] = await getTemperatureValue();
        currentTemperatureValue[1] = await getTemperatureValue1();
        print("获取温度:$currentTemperatureValue");
        currentHeatPower[0] = await getHeatPower();
        currentHeatPower[1] = await getHeatPower1();
        update();
      }

      // 更新超声波和剩余时间数据
      // currentUltrasonic1[0] = await getUltrasonic1();
      // currentUltrasonic1[1] = await getUltrasonic1();
      remainingtime[0] = await getremainingtime();
      remainingtime[1] = await getremainingtime1();
      // //机械臂传感器刷新
      // currentArmXPosition[0] = await getArmPositionXValue();
      // currentArmYPosition[0] = await getArmPositionYValue();
      // currentArmXPosition[1] = await getArmPositionXValue();
      // currentArmYPosition[1] = await getArmPositionYValue();

      await delayDuration.milliseconds.delay();
      c = DateTime.now().millisecondsSinceEpoch ~/ 1000;

      // 处理新进度事件
      if (_newProgressEventIn[containerId]) {
        print("=======task id:${currentTaskProgress[containerId].taskId}");

        // 任务开始事件（255为特殊标识）
        if (currentTaskProgress[containerId].taskId == 255) {
          if (currentTaskProgress[containerId].state == TaskState.WAITING) {
            deviceService.addSystemLog(containerId, "任务开始");
            print("---接收到任务开始事件---");
          }

          // 任务完成事件
          if (currentTaskProgress[containerId].state == TaskState.DONE) {
            print("---接收到任务结束事件---");
            deviceService.addSystemLog(containerId, "任务结束");
            done = true;
          } else if (currentTaskProgress[containerId].state ==
              TaskState.FAULT) {
            deviceService.addErrorLog(containerId, "任务错误");
          }
        }

        _newProgressEventIn[containerId] = false;
        lastTime = c;
      }

      // 超时检测（150分钟）
      if (c - lastTime > 150 * 60) {
        print("---未检测到步骤超时--");
        break;
      }

      // 任务完成处理
      if (done) {
        result = true;
        print("---结束--");
        break;
      }
    }

    // 清理任务状态
    working[containerId] = false;
    targetTemperatureValue[containerId] = 0;
    currentTemperatureValue[containerId] = 0;
    //机械臂传感器数据清理
    // currentArmXPosition[containerId] = 0;
    // currentArmYPosition[containerId] = 0;
    // working[containerId] = false; // 结束工作状态置为false
    update();
    deviceService.eventBus.fire(DeviceWorkEvent(false));
    return result;
  }

  // 传感器数据获取方法（双模块）
  Future<double> getTemperatureValue() async {
    return await deviceService.getSensorValue(
            deviceService.heaterId, deviceService.temperatureSensor) /
        100.00;
  }

  Future<double> getTemperatureValue1() async {
    return await deviceService.getSensorValue(
            deviceService.heaterId, deviceService.temperatureSensor1) /
        100.00;
  }

  Future<double> getHeatPower() async {
    return await deviceService.getSensorValue(
            deviceService.heaterId, deviceService.powerSensor) /
        100.00;
  }

  Future<double> getHeatPower1() async {
    return await deviceService.getSensorValue(
            deviceService.heaterId, deviceService.powerSensor1) /
        100.00;
  }

  Future<double> getUltrasonic1() async {
    return await deviceService.getSensorValue(
            deviceService.armComponentId, deviceService.ultrasonicSensor1) /
        1;
  }

  Future<double> getArmPositionXValue() async {
    return await deviceService.getSensorValue(
            deviceService.armComponentId, deviceService.armPositionXSensor) /
        1;
  }

  Future<double> getArmPositionYValue() async {
    return await deviceService.getSensorValue(
            deviceService.armComponentId, deviceService.armPositionYSensor) /
        1;
  }

  Future<double> getremainingtime() async {
    return await deviceService.getSensorValue(
            deviceService.waterSupportComponentId,
            deviceService.remainingtime) /
        1;
  }

  Future<double> getremainingtime1() async {
    return await deviceService.getSensorValue(
            deviceService.waterSupportComponentId,
            deviceService.remainingtime1) /
        1;
  }

  /// 中止任务
  Future<bool> abortTask(int containerId) async {
    if (!working[containerId] && !pause[containerId]) return true;

    deviceService.addSystemLog(containerId, "执行任务中止");
    final r = await deviceService.abortAction(containerId);
    deviceService.addSystemLog(containerId, "任务中止${r ? "成功" : "失败"}");

    if (!r) {
      // showHint("中止失败", HintType.WARNING);
      int? selectedIndex =
          await showSelectionDialog("终止失败,系统繁忙稍后重试,", "等待", "强行终止");
      if (selectedIndex == 0 || selectedIndex == null) {
        return false;
      }
      selectedIndex =
          await showSelectionDialog("界面模块是否已卡死，需要强行终止？", "取消", "确认");
      if (selectedIndex == 0 || selectedIndex == null) {
        return false;
      }
    }
    // 重置任务状态
    currentTaskProgress[containerId] =
        TaskProgress(containerId, -1, -1, TaskState.EMPTY);
    working[containerId] = false;
    pause[containerId] = false;

    // 重置所有样品位状态
    for (var i in sampleItems[containerId]) {
      for (var j in i) {
        j.state = TaskState.EMPTY;
      }
    }
    update();
    return true;
  }

  /// 暂停任务
  Future<bool> pauseTask(int containerId) async {
    if (pause[containerId]) return true;

    deviceService.addSystemLog(containerId, "执行任务暂停");
    final r = await deviceService.abortAction(containerId, isPause: true);
    deviceService.addSystemLog(containerId, "暂停中止${r ? "成功" : "失败"}");

    if (!r) {
      showHint("暂停失败", HintType.WARNING);
      return false;
    }

    deviceService.addSystemLog(containerId, "暂停中止${r ? "成功" : "失败"}");
    pause[containerId] = true;
    working[containerId] = false;
    update();
    return true;
  }

// 比较两个二维数组是否相等的辅助函数
  bool _areArraysEqual(List<List<bool>> arr1, List<List<bool>> arr2) {
    if (arr1.length != arr2.length) return false;

    for (int i = 0; i < arr1.length; i++) {
      if (arr1[i].length != arr2[i].length) return false;

      for (int j = 0; j < arr1[i].length; j++) {
        if (arr1[i][j] != arr2[i][j]) {
          return false;
        }
      }
    }

    return true;
  }

  /// 全选样品位
  void selectAll(int index) {
    for (var i in sampleItems[index]) {
      for (var j in i) {
        j.selected = true;
      }
    }
    update();
  }

  Future<bool> selectHave(int index) async {
    final detector = TubeDetector();
    bool success = false;

    try {
      //设置调试画面
      detector.setDebugMode(false);

      // 定义摄像头索引尝试顺序，优先尝试常用索引
      List<int> cameraIndices = [3, 2, 1, 0];
      bool cameraInitialized = false;

      // 尝试不同的摄像头索引
      for (int camIndex in cameraIndices) {
        if (detector.initialize(cameraIndex: camIndex)) {
          cameraInitialized = true;
          print('摄像头初始化成功，使用索引: $camIndex');
          break;
        } else {
          print('摄像头索引 $camIndex 初始化失败，尝试下一个...');
          // 短暂延迟后尝试下一个摄像头
          await Future.delayed(Duration(milliseconds: 100));
        }
      }

      if (!cameraInitialized) {
        print('所有摄像头索引尝试均失败');
        detector.dispose();
        update();
        return false;
      }

      // 开始检测
      if (detector.startDetection()) {
        int maxAttempts = 10;
        int stableCount = 0;
        List<List<bool>>? lastArr;
        List<List<bool>> stableArr = [];

        for (int attempt = 0; attempt < maxAttempts; attempt++) {
          if (stableCount >= 3) {
            success = true;
            break;
          }

          final result = detector.processSingleFrame();
          final states = detector.getCurrentTubeStates();

          // 检查是否获取到有效状态
          if (states.isEmpty || states.length < 36) {
            print('第 $attempt 次尝试：未获取到有效状态数据');
            await Future.delayed(Duration(milliseconds: 100));
            continue;
          }

          // 创建6x6二维数组
          List<List<bool>> currentArr = List.generate(6, (i) {
            return List.generate(6, (j) {
              int stateIndex = i * 6 + j;
              return stateIndex < states.length
                  ? states[stateIndex].hasTube
                  : false;
            });
          });

          // 比较当前数组与上一次数组是否相同
          if (lastArr != null && _areArraysEqual(lastArr, currentArr)) {
            stableCount++;
            stableArr = currentArr;
            print('检测到稳定状态 $stableCount/3');
          } else {
            stableCount = 0;
            print('状态不稳定，重置计数');
          }
          lastArr = currentArr;

          // 使用异步延迟
          await Future.delayed(Duration(milliseconds: 50));
        }

        detector.stopDetection();

        // 拷贝到三维数组的指定索引位置
        if (success) {
          print('检测成功，更新样本数据');
          for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 6; j++) {
              sampleItems[index][i][j].selected = stableArr[i][j];
            }
          }
        } else {
          print('检测失败：未能在 $maxAttempts 次尝试内获得稳定状态');
        }
      } else {
        print('开始检测失败');
      }
    } catch (e) {
      print('检测过程中发生错误: $e');
      success = false;
    } finally {
      detector.dispose();
    }

    update();
    return success;
  }

  /// 清除所有样品位选择
  void clearAll(int index) {
    for (var i in sampleItems[index]) {
      for (var j in i) {
        j.selected = false;
        j.state = TaskState.EMPTY;
      }
    }
    update();
  }
}

/// 样品位数据模型
class SampleItem {
  bool selected; // 是否选中
  String label; // 标签（位置编号）
  TaskState state; // 任务状态

  SampleItem(this.selected, this.label, this.state);
}
